package com.lry.basic.netty.protobuf.client;

import com.lry.basic.netty.protobuf.proto.Constant;
import com.lry.basic.netty.protobuf.proto.Msg;
import com.lry.basic.netty.protobuf.proto.MsgType;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.SingleThreadEventExecutor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/9/30
 */
@ChannelHandler.Sharable
public class ClientHandler extends SimpleChannelInboundHandler<Msg.Request> {
    private static String username;
    ExecutorService exec = Executors.newSingleThreadExecutor();
    @Override
    protected void channelRead0(final ChannelHandlerContext ctx, Msg.Request request) throws Exception {
        int msgType = request.getType();
        //注册响应
        if(msgType==MsgType.REGISTER_RESP.value()){
            if(Constant.REGISTER_SUCCESS.equals(request.getMsg())){
                System.out.println("register success");
                System.out.println("登录指令示范：login 用户名 密码");
            }else{
                System.out.println("register fail");
            }
        }
        //登录响应
        else if(msgType==MsgType.LOGIN_RESP.value()){
                if(Constant.LOGIN_SUCCESS.equals(request.getMsg())){
                    username = request.getReceiver();
                    System.out.println("login success");
                    System.out.println("发送指令示范：send 接收者(发送给所有人写all) 发送内容");
                }else{
                    System.out.println("login fail");
                }
        }
        //发送响应
        else if(msgType==MsgType.SEND_RESP.value()){
            System.out.println(request.getMsg());
        }
        //接收别人的消息
        else if(msgType==MsgType.RECEIVE_RESP.value()){
            String sendName = request.getUsername();
            String msg = request.getMsg();
            System.out.println("接收到"+sendName+"的消息："+msg);
        }

        exec.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    handlerCommend(ctx);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("注册指令示范：register 用户名 密码");
        System.out.println("登录指令示范：login 用户名 密码");
        System.out.println("发送指令示范：send 接收者(发送给所有人写all) 发送内容");
        handlerCommend(ctx);
    }


    private void handlerCommend(ChannelHandlerContext ctx) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String commendStr = reader.readLine();
        String[] splits = commendStr.split(" ");
        String commend = splits[0];
        Msg.Request req = null;
        switch (commend){
            //注册
            case Constant.REGISTER:
                if(splits.length!=3){
                    System.out.println("指令错误,正确示范：register 用户名 密码");
                    handlerCommend(ctx);
                }
                req = buildRegisterReq(splits[1],splits[2]);
                ctx.writeAndFlush(req);
            break;
            //登录
            case Constant.LOGIN:
                if(splits.length!=3){
                    System.out.println("指令错误,正确示范：login 用户名 密码");
                    handlerCommend(ctx);
                }
                req = buildLoginReq(splits[1],splits[2]);
                ctx.writeAndFlush(req);
            break;

            case Constant.SEND:
                if(splits.length!=3){
                    System.out.println("指令错误,正确示范：send 接收者 内容");
                    handlerCommend(ctx);
                }
                if(username.equals(splits[1])){
                    System.out.println("指令错误：接收者和发送者一样");
                    handlerCommend(ctx);
                }
                req = buildSendMsg(splits[1],splits[2]);
                ctx.writeAndFlush(req);
            break;

            default:
                System.out.println("指令错误");
                System.out.println("注册指令示范：register 用户名 密码");
                System.out.println("登录指令示范：login 用户名 密码");
                System.out.println("发送指令示范：send 接收者(发送给所有人写all) 发送内容");
                handlerCommend(ctx);
            break;
        }
    }

    private Msg.Request buildSendMsg(String receiver, String content) {
        Msg.Request req = Msg.Request.newBuilder().
                setUsername(username).//发送者
                setType(MsgType.SEND_REQ.value()).
                setReceiver(receiver).//接收者
                setMsg(content).
                build();
        return req;
    }

    private Msg.Request buildLoginReq(String username, String pwd) {
        Msg.Request req = Msg.Request.newBuilder().
                setType(MsgType.LOGIN_REQ.value()).
                setUsername(username).
                setPassword(pwd).
                setMsg("login").
                setReceiver("server").
                build();
        return req;
    }

    private Msg.Request buildRegisterReq(String username, String pwd) {
        Msg.Request req = Msg.Request.newBuilder().
                setType(MsgType.REGISTER_REQ.value()).
                setUsername(username).
                setPassword(pwd).
                setMsg("register").
                setReceiver("server").
                build();
        return req;
    }

}
